package cn.iocoder.yudao.module.erp.service.costinfo;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.erp.controller.admin.costinfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.costinfo.CostInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.costinfo.CostInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 其他费用 Service 实现类
 *
 * @author 王1
 */
@Service
@Validated
public class CostInfoServiceImpl implements CostInfoService {

    @Resource
    private CostInfoMapper costInfoMapper;

    @Override
    public Long createCostInfo(CostInfoSaveReqVO createReqVO) {
        // 插入
        CostInfoDO costInfo = BeanUtils.toBean(createReqVO, CostInfoDO.class);
        costInfo.setStatus(0L);//未入账
        if(costInfo.getAmountType()==0){
            costInfo.setAmount(costInfo.getAmount().abs());
        }else if(costInfo.getAmountType()==1){
            costInfo.setAmount(costInfo.getAmount().abs().negate());
        }
        costInfoMapper.insert(costInfo);
        // 返回
        return costInfo.getId();
    }

    @Override
    public void updateCostInfo(CostInfoSaveReqVO updateReqVO) {
        // 校验存在
        CostInfoDO old=costInfoMapper.selectById(updateReqVO.getId());
        if (old == null) {
            throw exception(COST_INFO_NOT_EXISTS);
        }
        if(old.getStatus()!=0){
            throw exception(new ErrorCode(1_030_400_014, "已入账的费用不可修改"));
        }
        // 更新
        CostInfoDO costInfo = BeanUtils.toBean(updateReqVO, CostInfoDO.class);

        if(costInfo.getAmountType()==0){
            costInfo.setAmount(costInfo.getAmount().abs());
        }else if(costInfo.getAmountType()==1){
            costInfo.setAmount(costInfo.getAmount().abs().negate());
        }

        costInfoMapper.updateById(costInfo);
    }

    @Override
    public void deleteCostInfo(Long id) {
        // 校验存在
        validateCostInfoExists(id);
        // 删除
        costInfoMapper.deleteById(id);
    }

    private void validateCostInfoExists(Long id) {
        if (costInfoMapper.selectById(id) == null) {
            throw exception(COST_INFO_NOT_EXISTS);
        }
    }

    @Override
    public CostInfoDO getCostInfo(Long id) {
        return costInfoMapper.selectById(id);
    }

    @Override
    public PageResult<CostInfoDO> getCostInfoPage(CostInfoPageReqVO pageReqVO) {
        return costInfoMapper.selectPage(pageReqVO);
    }

}